<template>
  <div class="supplier-container base-page-container">
    <el-container style="height: 100%;">
      <el-aside width="179px" style="height: 100%;display: flex;flex-direction: column;">
        <div class="nav">
          <div class="title-box">商品类别</div>
          <el-input v-model="typeSearch" placeholder="分类查询"/>
        </div>
        <div class="tree-box">
          <el-tree
              :data="treeData"
              :props="defaultProps"
              @node-click="handleNodeClick"
          />
        </div>
      </el-aside>
      <el-main style="height: 100%;display: flex;flex-direction: column;">
        <!-- 搜索区域 -->
        <common-search
            v-model="searchForm"
            :search-items="searchItemsConfig"
            @search="handleSearch"
            @reset="fetchTableData"
        >
          <!-- 自定义插槽示例 -->
          <template #customSlot="{ form }">
            <!-- 这里可以放置自定义搜索组件 -->
            <el-select v-model="form.customField" placeholder="自定义字段" style="width: 230px">
              <el-option label="选项1" value="1"/>
              <el-option label="选项2" value="2"/>
            </el-select>
          </template>
        </common-search>

        <!-- 操作按钮区域 -->
        <action-buttons
            :action-permissions="actionPermissions"
            add-type="success"
            :export-type="themeType"
            :import-type="themeType"
            :enable-type="themeType"
            :disable-type="themeType"
            @add="handleGoDetail(null, 'add')"
            @export="handleExport"
            @import="handleImport"
            @enable="handleEnable"
            @disable="handleDisable"
        />

        <!-- 表格区域 -->
        <custom-table
            height="200"
            :data="tableData"
            :columns="tableColumns"
            :loading="tableLoading"
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            @selection-change="handleSelectionChange"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        >
          <!-- 状态列的自定义插槽 -->
          <template #status="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'info'">
              {{ row.status }}
            </el-tag>
          </template>

          <!-- 操作列 -->
          <template #operation="{ row }">
            <theme-button v-if="tablePermissions.edit" link @click="handleGoDetail(row, 'edit')">编辑</theme-button>
            <theme-button v-if="tablePermissions.view" link @click="handleGoDetail(row, 'view')">查看</theme-button>
            <theme-button v-if="tablePermissions.log" link @click="handleLog(row)">日志</theme-button>
          </template>
        </custom-table>
      </el-main>
    </el-container>
    <!-- 日志弹窗 -->
    <log-dialog
        v-model:visible="logDialogVisible"
        :log-data="logData"
        :total="logPagination.total"
        :current-page="logPagination.currentPage"
        :page-size="logPagination.pageSize"
        @size-change="handleLogSizeChange"
        @current-change="handleLogCurrentChange"
    />
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed} from 'vue'
import {useTheme} from '@/hooks/useTheme'
import {useRouter} from "vue-router";

// 使用主题组合API
const {themeType} = useTheme()
const router = useRouter()
// 搜索项配置列表
const searchItemsConfig = [
  {
    label: '商品编号',
    prop: 'code',
    type: 'el-input',
    placeholder: '请输入商品编号',
    defaultVisible: true
  },
  {
    label: '商品名称',
    prop: 'name',
    type: 'el-input',
    placeholder: '请输入商品名称',
    defaultVisible: true
  },
  {
    label: '状态',
    prop: 'status',
    type: 'el-select',
    placeholder: '请选择状态',
    defaultVisible: true,
    options: [
      {label: '请选择状态', value: ''},
      {label: '启用', value: '启用'},
      {label: '停用', value: '停用'}
    ]
  },
  {
    label: '是否启用批次',
    prop: '',
    type: 'el-select',
    placeholder: '请选择状态',
    defaultVisible: true,
    options: [
      {label: '请选择状态', value: ''},
      {label: '是', value: '是'},
      {label: '否', value: '否'}
    ]
  },
  {
    label: '是否启用序列号',
    prop: '',
    type: 'el-select',
    placeholder: '请选择状态',
    defaultVisible: true,
    options: [
      {label: '请选择状态', value: ''},
      {label: '是', value: '是'},
      {label: '否', value: '否'}
    ]
  },
  {
    label: '商品条码',
    prop: '',
    type: 'el-input',
    placeholder: '请输入商品条码',
    defaultVisible: true
  },
  {
    label: '货主',
    prop: 'owner',
    type: 'el-select',
    placeholder: '请输入货主',
    defaultVisible: false,
    options: [
      {label: '货主A', value: '货主A'},
      {label: '货主B', value: '货主B'},
      {label: '货主C', value: '货主C'}
    ]
  },
  {
    label: '标签',
    prop: '',
    type: 'el-select',
    placeholder: '请输入标签',
    defaultVisible: false,
    options: [
      {label: '标签A', value: '标签A'},
      {label: '标签B', value: '标签B'}
    ]
  },
  {
    label: '备注',
    prop: '',
    type: 'el-input',
    placeholder: '请输入商品备注',
    defaultVisible: false
  }
]

// 搜索表单数据
const searchForm = reactive({
  code: '',
  name: '',
  status: '',
  createDate: '',
  owner: '',
  contactPerson: '',
  contactPhone: '',
  dateRange: [],
  customField: ''
})

// 查询操作
const handleSearch = () => {
  pagination.currentPage = 1
  fetchTableData()
}

// 表格加载状态
const tableLoading = ref(false)

// 表格数据
const tableData = ref([
  {
    id: 1,
    code: 'GYS11011',
    name: '供应商A',
    owner: '货主A',
    status: '启用',
    contactPerson: '王阳明',
    contactPhone: '13587584785',
    contactAddress: '浙江省杭州市西湖区西湖大道XX路',
    remark: ''
  }
])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
})

// 分页大小变更事件
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchTableData()
}

// 页码变更事件
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchTableData()
}

// 获取表格数据
const fetchTableData = () => {
  tableLoading.value = true

  // 构造查询参数
  const params = {
    page: pagination.currentPage,
    pageSize: pagination.pageSize,
    ...searchForm
  }

  // 处理日期范围
  if (params.dateRange && params.dateRange.length === 2) {
    params.startDate = params.dateRange[0]
    params.endDate = params.dateRange[1]
    delete params.dateRange
  }

  console.log('查询参数:', params)

  // 这里应该调用接口获取数据
  // 示例使用模拟数据
  setTimeout(() => {
    // 生成演示数据
    tableData.value = Array.from({length: pagination.pageSize}).map((_, index) => ({
      id: index + 1 + (pagination.currentPage - 1) * pagination.pageSize,
      code: `GYS${10000 + index}`,
      name: `供应商${String.fromCharCode(65 + index % 26)}`,
      owner: '货主A',
      status: index % 3 ? '启用' : '停用',
      contactPerson: '王阳明',
      contactPhone: '13587584785',
      contactAddress: '浙江省杭州市西湖区西湖大道XX路',
      remark: index % 2 ? '优质供应商' : ''
    }))

    tableLoading.value = false
  }, 300)
}

// 选中的行数据
const selectedRows = ref([])

// 表格多选事件
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
}


// 编辑按钮事件
const handleGoDetail = (row, type) => {
  router.push({
    path: '/commodity/detail',
    query: {
      mode: type,  // 或 'edit' 或 'view',add
      id: '123'    // 编辑和查看时需要传id
    }
  })
}


// 日志弹窗可见性
const logDialogVisible = ref(false)

// 日志数据
const logData = ref([])

// 日志分页数据
const logPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 查看日志按钮事件
const handleLog = (row) => {
  logDialogVisible.value = true
  fetchLogData(row)
}

// 获取日志数据
const fetchLogData = (row) => {
  // 这里应该调用接口获取数据
  // 示例使用模拟数据
  setTimeout(() => {
    // 生成演示数据
    const currentDate = '2024-01-01 00:00:00'
    logData.value = [
      {
        id: 1,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `修改供应商 [${row.name}]`
      },
      {
        id: 2,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `新增供应商 [${row.name}]`
      },
      {
        id: 3,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `[操作]供应商 [${row.name}]`
      },
      {
        id: 4,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `[操作]供应商 [${row.name}]`
      },
      {
        id: 5,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `[操作]供应商 [${row.name}]`
      },
      {
        id: 6,
        operateTime: currentDate,
        operator: '王阳明',
        operateContent: `[操作]供应商 [${row.name}]`
      }
    ]

    logPagination.total = 6
  }, 300)
}

// 日志分页大小变更事件
const handleLogSizeChange = (val) => {
  logPagination.pageSize = val
  // 重新获取日志数据
}

// 日志页码变更事件
const handleLogCurrentChange = (val) => {
  logPagination.currentPage = val
  // 重新获取日志数据
}

// 删除按钮事件
const handleDelete = (row) => {
  let confirmText
  if (row) {
    confirmText = `确定要删除供应商 ${row.name} 吗?`
  } else {
    if (selectedRows.value.length === 0) {
      ElMessage.warning('请至少选择一个供应商')
      return
    }
    confirmText = `确定要删除选中的 ${selectedRows.value.length} 个供应商吗?`
  }

  ElMessageBox.confirm(confirmText, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用删除接口
    ElMessage.success('删除成功')
    fetchTableData()
  }).catch(() => {
  })
}

// 启用按钮事件
const handleEnable = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个供应商')
    return
  }

  ElMessageBox.confirm(`确定要启用选中的 ${selectedRows.value.length} 个供应商吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用启用接口
    ElMessage.success('启用成功')
    fetchTableData()
  }).catch(() => {
  })
}

// 停用按钮事件
const handleDisable = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一个供应商')
    return
  }

  ElMessageBox.confirm(`确定要停用选中的 ${selectedRows.value.length} 个供应商吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用停用接口
    ElMessage.success('停用成功')
    fetchTableData()
  }).catch(() => {
  })
}

// 导出按钮事件
const handleExport = () => {
  ElMessage.success('导出功能开发中')
}

// 导入按钮事件
const handleImport = () => {
  ElMessage.success('导入功能开发中')
}


// 权限控制数据 - 默认权限设置
const actionPermissions = reactive({
  add: true,      // 新增权限
  export: true,   // 导出权限
  import: true,   // 导入权限
  enable: true,   // 启用权限
  disable: true,  // 停用权限
  delete: true   // 删除权限
})

// 表格操作权限 - 默认权限设置
const tablePermissions = reactive({
  edit: true,
  view: true,
  log: true
})

// 表格列配置
const tableColumns = [
  {prop: 'name', label: '商品名称', minWidth: 120, visible: true},
  {prop: 'code', label: '商品编号', width: 120, minWidth: '120', visible: true},
  {prop: 'barcode', label: '商品条码', width: 120, minWidth: '120', visible: true},
  {prop: 'owner', label: '货主', width: 100, minWidth: '100', visible: true},
  {prop: 'category', label: '分类', width: 100, minWidth: '100', visible: true},
  {prop: 'brand', label: '品牌', width: 100, minWidth: '100', visible: true},
  {prop: 'unit', label: '单位', width: 80, minWidth: '80', visible: true},
  {prop: 'tag', label: '商品标签', width: 100, minWidth: '100', visible: true},
  {prop: 'status', label: '状态', width: 80, minWidth: '80', visible: true},
  {prop: 'batchManage', label: '批次管理', width: 100, minWidth: '100', visible: true},
  {prop: 'composition', label: '序列号管理', width: 100, minWidth: '100', visible: true},
  {prop: 'remark', label: '备注', width: '150', minWidth: '150', visible: true},
  {prop: 'operation', label: '操作', width: '160', minWidth: '160', fixed: 'right', visible: true}
]
// ... existing code ...

// 分类查询
const typeSearch = ref('')

// tree
const treeData = [
  {
    label: 'Level one 1',
    children: [
      {
        label: 'Level two 1-1',
        children: [
          {
            label: 'Level three 1-1-1',
          },
        ],
      },
    ],
  },
  {
    label: 'Level one 2',
    children: [
      {
        label: 'Level two 2-1',
        children: [
          {
            label: 'Level three 2-1-1',
          },
        ],
      },
      {
        label: 'Level two 2-2',
        children: [
          {
            label: 'Level three 2-2-1',
          },
        ],
      },
    ],
  },
  {
    label: 'Level one 3',
    children: [
      {
        label: 'Level two 3-1',
        children: [
          {
            label: 'Level three 3-1-1',
          },
        ],
      },
      {
        label: 'Level two 3-2',
        children: [
          {
            label: 'Level three 3-2-1',
          },
        ],
      },
    ],
  },
]
const treeValue = ref('')

const defaultProps = {
  children: 'children',
  label: 'label',
}

const handleNodeClick = (res) => {
  console.log(res)
  if (!res.children?.length) {
    treeValue.value = res.label
  }
}
// 页面初始化
onMounted(async () => {
  fetchTableData()
})
</script>

<style lang="scss" scoped>
/* 使用全局样式类，保留特殊样式覆盖 */
.base-page-container {
  padding-left: 0;
  padding-top: 0;
}

.el-aside {

  .nav {
    display: flex;
    flex-direction: column;
    align-items: center;

    .title-box {
      width: 179px;
      height: 42px;
      background: #F0F6FF;
      padding: 10px 20px;
      box-sizing: border-box;
      font-weight: 400;
      font-size: var(--el-font-size-base);
      color: #000000;
    }

    .el-input {
      width: 150px;
      margin: 10px 0;
    }

    :deep(.el-input__wrapper) {
      text-align: center;
      border-radius: 30px;
    }
  }

  .tree-box {
    padding: 0 5px;
    flex: 1;
    overflow: auto;
  }

}

.el-main {
  padding-top: 20px;
  padding-left: 5px;
}
</style>